<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { InputPassword } from '@/components/InputPassword'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag, ElMessageBox } from 'element-plus'
import { Table } from '@/components/Table'
import { h, ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  adminListApi,
  adminAddApi,
  adminEditApi,
  adminDelApi,
  adminDeptListApi,
  adminBatchDelApi,
  stateApi,
  adminEditPasswordApi
} from '@/api/admin'
import { roleListApi } from '@/api/role'
import { TableData } from '@/api/admin/types'
import { useTable } from '@/hooks/web/useTableTest'

const password = ref('')
const { register, tableObject, methods } = useTable<
  {
    count: number
    data: TableData[]
  },
  TableData
>({
  getListApi: adminListApi,
  // delListApi: adminDelApi,
  response: {
    count: 'count',
    data: 'data'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const menuData = ref<any>([])
const deptList = async () => {
  const res = await adminDeptListApi({})
    .catch(() => {})
    .finally(() => {})
  if (res) {
    menuData.value = res.data
  }
}
deptList()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'admin_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'dept_id',
    label: '所属部门',
    form: {
      component: 'TreeSelect',
      componentProps: {
        data: menuData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'dept_id',
        props: {
          children: 'children',
          label: 'dept_name'
        }
      }
    },
    table: {
      show: false
    },
    search: {
      component: 'TreeSelect',
      componentProps: {
        data: menuData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'dept_id',
        props: {
          children: 'children',
          label: 'dept_name'
        }
      },
      show: true
    }
  },
  {
    field: 'dept_name',
    label: '所属部门',
    form: {
      show: false
    }
  },
  {
    field: 'role_name',
    label: '所属角色',
    form: {
      show: false
    }
  },
  {
    field: 'role_id',
    label: '所属角色',
    table: {
      show: false
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: roleListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择所属角色（双击选择）',
        nameField: 'role_name',
        valueField: 'role_id',
        crudSchemas: [
          {
            field: 'role_name',
            label: '角色名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: roleListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择所属角色（双击选择）',
        nameField: 'role_name',
        valueField: 'role_id',
        crudSchemas: [
          {
            field: 'role_name',
            label: '角色名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    }
  },
  {
    field: 'username',
    label: '用户名',
    search: {
      show: true
    }
  },
  {
    field: 'nickname',
    label: '姓名',
    search: {
      show: true
    }
  },
  {
    field: 'is_stop',
    label: t('是否停用'),
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return h(
        ElTag,
        {
          type: cellValue === '0' ? 'success' : 'warning'
        },
        () => (cellValue === '0' ? t('停用') : t('启用'))
      )
    },
    table: {
      show: false
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '停用',
            value: '0'
          },
          {
            label: '启用',
            value: '1'
          }
        ]
      }
    }
  },
  {
    field: 'email',
    label: '电子邮箱',
    width: 160
  },
  {
    field: 'mobile',
    label: '手机号',
    width: 160,
    type: 'phone'
  },
  {
    field: 'action',
    width: '480px',
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogVisiblePassword = ref(false)
const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.admin_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await adminBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'add':
      dialogTitle.value = t('新增')
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      deptList()
      break
    case 'edit':
      dialogTitle.value = t('编辑')
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'detail':
      dialogTitle.value = t('详情')
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      // tableObject.currentRow = row
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.admin_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'password':
      dialogTitle.value = t('修改密码')
      tableObject.currentRow = row
      dialogVisiblePassword.value = true
      break
    default:
      break
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  if (actionType.value == 'add') {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await write?.getFormData()) as TableData
        const res = await adminAddApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  } else if (actionType.value == 'edit') {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await write?.getFormData()) as TableData
        const res = await adminEditApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  } else if (actionType.value == 'password') {
    loading.value = true
    const res = await adminEditPasswordApi({
      admin_id: tableObject.currentRow!.admin_id,
      password: password.value
    })
      .catch(() => {})
      .finally(() => {
        loading.value = false
        // password.value = ''
        // dialogVisiblePassword.value = false
      })
    if (res) {
      // dialogVisiblePassword.value = false
      // password.value = ''
      getList()
    }
    password.value = ''
    dialogVisiblePassword.value = false
  }
}
const apiDel = async (admin_id) => {
  let delRes = await adminDelApi({ admin_id: admin_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const stateData = async (admin_id) => {
  let is_stop: any = ''
  if (admin_id.is_stop == '0') {
    is_stop = '1'
  } else {
    is_stop = '0'
  }
  let res = await stateApi({ admin_id: admin_id.admin_id, is_stop: is_stop })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    getList()
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action('edit', row)">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action('detail', row)">
          {{ t('exampleDemo.detail') }}
        </ElButton>
        <ElButton type="warning" @click="stateData(row)">
          {{ row.is_stop === '0' ? t('停用') : t('启用') }}
        </ElButton>
        <ElButton type="warning" @click="action('password', row)">
          {{ t('修改密码') }}
        </ElButton>

        <ElButton type="danger" @click="action('del', row)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisiblePassword" :title="dialogTitle">
    <InputPassword v-model="password" strength />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <!-- <ElButton @click="closePassword">{{ t('dialogDemo.close') }}</ElButton> -->
      <ElButton @click="dialogVisiblePassword = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
